package com.flower.service.impl;

import org.springframework.stereotype.Service;

import com.flower.mapper.IProductDao;
import com.flower.pojo.PageBean;
import com.flower.pojo.Product;
import com.flower.service.IProductService;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

@Service("productService")
public class ProductServiceImpl implements IProductService {

    @Resource(name = "IProductDao")
    private IProductDao iProductDao;

    @Override
    public List<Product> findHotProduct() {
        return iProductDao.findHotProduct();
    }

    @Override
    public List<Product> findNewProduct() {
        return iProductDao.findNewProduct();
    }
    
	@Override
	public List<Product> findBargainProduct() {
		return iProductDao.findBargainProduct();
	}

    @Override
    public PageBean findAllProductByCid(int cid, int currPageNO) {
        PageBean<Product> pageBean = new PageBean<>();

        //封装当前页号
        pageBean.setCurrPageNO(currPageNO);

        //封装页面大小
        pageBean.setPerPageNO(8);

        //封装总记录数
        int allRecordNO = 0;
        if(cid == 0){
        	//获取所有商品的总记录数
        	allRecordNO = iProductDao.getAllNum();
        }else{
        	//通过cid获取不同类别商品的总记录数
        	allRecordNO = iProductDao.getAllRecordNO(cid);
        }
        pageBean.setAllRecordNO(allRecordNO);
        //System.out.println("allRecordNO = " + allRecordNO);

        //封装总页数
        int allPageNO = 0;
        //总记录数 % 页面大小
        if(pageBean.getAllRecordNO() % pageBean.getPerPageNO() == 0){
            allPageNO = pageBean.getAllRecordNO() / pageBean.getPerPageNO();
        }else {
            allPageNO = pageBean.getAllRecordNO() / pageBean.getPerPageNO() + 1;
        }
        pageBean.setAllPageNO(allPageNO);
        //System.out.println("allPageNO = " + allPageNO);

        //封装页面内容
        //start,size -> limit start,size
        int size = pageBean.getPerPageNO();
        int start = (pageBean.getCurrPageNO()-1) * size;  //(当前页号-1) * 页面大小
        
        List<Product> list = new ArrayList<Product>();
        if(cid == 0){
        	list = iProductDao.findAllProduct(start, size);
        }else{
        	list = iProductDao.findAllProductByCid(cid, start, size);
        }
        pageBean.setData(list);

        return pageBean;
    }

    @Override
    public Product findProductByPid(int pid) {
        Product product = iProductDao.findProductByPid(pid);
        return product;
    }

}
